'use strict'

const { ApiController } = require('jax')
const axios = require('axios')
const crypto = require('crypto')

class Controller extends ApiController {
  // 坐标转换
  async translate() {
    const { ctx } = this
    const { query } = this.ctx

    const result = await this.http('/ws/coord/v1/translate', {
      type: '3',
      ...query,
    }).then((res) => {
      return res.data
    })

    ctx.body = {
      code: 0,
      msg: 'success',
      data: result.locations,
    }
  }

  // 逆地址解析
  async geocoder() {
    const { ctx } = this
    const { query } = this.ctx

    const result = await this.http('/ws/geocoder/v1/', {
      get_poi: '1',
      ...query,
    }).then((res) => {
      return res.data
    })

    ctx.body = {
      code: 0,
      msg: 'success',
      data: result.result,
    }
  }

  async http(path, params) {
    const query = {
      ...params,
      key: 'WQ6BZ-KXUYC-DHI2O-AHJND-U26YV-FMFV5',
    }

    // 计算签名
    const sig = calculateSignature(query, path, 'a5FQ6XMHhzCudGA6vKz9RSQVz4uT8kzr')

    // 添加签名到参数
    query.sig = sig

    return axios({
      url: `https://apis.map.qq.com` + path,
      params: query,
    })
  }
}

// 计算签名
function calculateSignature(params, path, sk) {
  // 1. 对参数按key升序排序
  const sortedParams = Object.keys(params)
    .sort()
    .reduce((acc, key) => {
      acc[key] = params[key]
      return acc
    }, {})

  // 2. 拼接参数字符串
  const paramString = Object.entries(sortedParams)
    .map(([key, value]) => `${key}=${value}`)
    .join('&')

  // 3. 拼接待签名字符串
  const stringToSign = `${path}?${paramString}${sk}`

  // 4. 计算MD5
  const sig = crypto.createHash('md5').update(stringToSign).digest('hex')

  return sig
}

module.exports = Controller
